import { 
  ModelConfigInfo, 
  ModelConfigRequest, 
  ModelConfigResponse, 
  ModelConfigListResponse,
  ModelTestResult,
  ModelTemplate,
  ModelDiscoveryResult,
  ValidationRule
} from '@/types/model-config';
// import apiKeyService from './api-key.service'; // 后端/keys端点未实现，暂时禁用
import securityUtils from '@/utils/security.utils';
import { v4 as uuidv4 } from 'uuid';

// 配置验证规则
const VALIDATION_RULES: ValidationRule[] = [
  { field: 'providerId', type: 'required', message: 'Provider ID is required' },
  { field: 'providerName', type: 'required', message: 'Provider name is required' },
  { field: 'baseUrl', type: 'url', message: 'Valid base URL is required' },
  { field: 'apiKey', type: 'required', message: 'API key is required' },
  { field: 'modelName', type: 'required', message: 'Model name is required' },
  { field: 'modelName', type: 'pattern', message: 'Invalid model name format', pattern: /^[a-zA-Z0-9\-_.]+$/ }
];

// 恶意内容检测模式
const MALICIOUS_PATTERNS = [
  /<script[^>]*>.*?<\/script>/gi,
  /javascript:/gi,
  /on\w+\s*=/gi,
  /eval\s*\(/gi,
  /Function\s*\(/gi,
  /\bexec\s*\(/gi,
  /\\x[0-9a-fA-F]{2}/g,
  /\\u[0-9a-fA-F]{4}/g
];

// 安全的URL模式
const SAFE_URL_PATTERN = /^https?:\/\/[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]+$/;

const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8002/api/v1'; // 使用环境变量

// 注意：不再在前端定义演示配置
// 所有模型配置应该从后端 API 返回
// 后端可以预配置演示模型，让移动端和电脑端保持一致

class ModelConfigService {
  private useMockData = false; // 使用真实API
  private debugMode = true; // 开启调试模式
  private rateLimitCache: Map<string, { count: number; resetTime: number }> = new Map();
  private readonly RATE_LIMIT_MAX = 20; // requests per minute
  private readonly MAX_IMPORT_SIZE = 5 * 1024 * 1024; // 5MB
  private readonly MAX_IMPORT_CONFIGS = 100; // maximum configs per import
  /**
   * 获取可用的AI模型列表（用于生成提示）
   */
  async getAvailableModels(): Promise<ModelConfigInfo[]> {
    try {
      // 先尝试从新的hints API获取（不需要认证）
      const hintsApiUrl = `${API_BASE.replace('/model-configs', '/ai/available-models')}`;
      console.log('🔄 Fetching available models from hints API:', hintsApiUrl);

      const response = await fetch(hintsApiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
        // 不需要Authorization header
      });

      if (response.ok) {
        const models = await response.json();
        console.log(`✅ Found ${models.length} available models from hints API`);

        // 转换为ModelConfigInfo格式
        return models.map((model: any) => ({
          id: model.id,
          providerId: model.provider,
          providerName: model.provider,
          baseUrl: '',  // hints API不返回这些敏感信息
          apiKey: '',
          modelName: model.model_name,
          displayName: model.name,
          isActive: model.enabled,
          status: model.status || 'unknown',
          createdAt: new Date(),
          updatedAt: new Date()
        } as ModelConfigInfo));
      }
    } catch (error) {
      console.error('Failed to get available models from hints API:', error);
    }

    // 如果hints API失败，回退到原来的方法
    try {
      // 获取所有模型配置
      const allConfigs = await this.getModelConfigs();

      // 过滤出启用且健康的模型
      const availableModels = allConfigs.filter(config =>
        config.isActive &&
        (config.status === 'healthy' || config.status === 'unknown')
      );

      if (this.debugMode) {
        console.log(`✅ Found ${availableModels.length} available models for hints generation`);
      }

      return availableModels;
    } catch (error) {
      console.error('Failed to get available models:', error);
      // 返回空数组，界面会显示"暂无可用模型"
      return [];
    }
  }

  /**
   * 获取所有模型配置
   */
  async getModelConfigs(): Promise<ModelConfigInfo[]> {
    try {
      const apiUrl = `${API_BASE}/model-configs`;
      console.log('🌐 [Service] API_BASE:', API_BASE);
      console.log('🌐 [Service] 完整API URL:', apiUrl);
      console.log('🌐 [Service] 当前页面URL:', window.location.href);

      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      });

      console.log('📡 [Service] Response status:', response.status);
      console.log('📡 [Service] Response ok:', response.ok);

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ API error: ${response.status} ${response.statusText}`);
        console.error(`❌ Error body:`, errorText);
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const results = await response.json();
      console.log('📦 [Service] API返回的原始数据:', results);
      console.log('📦 [Service] 数据类型:', Array.isArray(results) ? 'Array' : typeof results);
      console.log('📦 [Service] 数据长度:', Array.isArray(results) ? results.length : 'N/A');

      // Transform backend response to frontend format
      if (Array.isArray(results)) {
        const configs = results.map(result => ({
          id: result.id || uuidv4(),
          providerId: result.provider,
          providerName: result.provider_name || result.provider,
          baseUrl: result.api_base,
          apiKey: result.api_key,
          modelName: result.model_name,
          displayName: result.name,
          isActive: result.enabled,
          maxTokens: result.max_tokens,
          temperature: result.temperature,
          topP: result.top_p,
          description: result.description,
          tags: result.tags || [],
          createdAt: new Date(result.created_at || Date.now()),
          updatedAt: new Date(result.last_updated || Date.now()),
          status: result.status || 'unknown' as const,
          lastChecked: result.last_checked ? new Date(result.last_checked) : null
        })) as ModelConfigInfo[];

        console.log(`✅ 从API加载了 ${configs.length} 个模型配置`);
        console.log('📋 转换后的配置详情:', configs.map(c => ({
          id: c.id,
          name: c.displayName,
          isActive: c.isActive,
          status: c.status
        })));
        return configs;
      }

      console.warn('⚠️ API返回格式不是数组，返回空列表');
      return [];
    } catch (error) {
      console.error('❌ Failed to fetch model configurations:', error);
      // 返回空数组，让UI显示"暂无模型"提示
      return [];
    }
  }

  /**
   * 创建新的模型配置（带验证和错误处理）
   */
  async createModelConfig(config: ModelConfigRequest): Promise<ModelConfigInfo> {
    console.log('[CREATE_CONFIG] Method called with:', { ...config, apiKey: '***masked***' });
    
    try {
      // 暂时跳过客户端验证，让后端处理验证
      // const validation = this.validateConfig(config);
      // console.log('[CREATE_CONFIG] Validation result:', validation);
      
      // if (!validation.valid) {
      //   console.error('[CREATE_CONFIG] Validation failed:', validation.errors);
      //   throw new Error(`Validation failed: ${validation.errors.join(', ')}`);
      // }
      
      console.log('[CREATE_CONFIG] Skipping client validation for testing');
      
      console.log('[CREATE_CONFIG] Sending config to backend:', { ...config, apiKey: '***masked***' });

      const response = await fetch(`${API_BASE}/model-configs`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        },
        body: JSON.stringify({
          displayName: config.displayName || config.modelName,  // 后端期待的是displayName
          name: config.displayName || config.modelName,  // 兼容性保留
          providerId: config.providerId,
          provider: config.providerId,
          providerName: config.providerName,
          provider_name: config.providerName,
          modelName: config.modelName,
          model_name: config.modelName,
          apiKey: config.apiKey,
          api_key: config.apiKey,
          baseUrl: config.baseUrl,
          api_base: config.baseUrl,
          temperature: config.temperature || 0.7,
          maxTokens: config.maxTokens || 2000,
          max_tokens: config.maxTokens || 2000,
          topP: config.topP || 1.0,
          top_p: config.topP || 1.0,
          isActive: config.isActive !== false,
          enabled: config.isActive !== false,
          description: config.description || '',
          status: config.status || 'unknown',  // 传递状态字段
          last_checked: config.lastChecked,     // 传递最后检查时间
          provider_config: {},
          extra_params: {}
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('[ERROR] API Response:', response.status, errorText);
        throw new Error(`Failed to create configuration: ${response.status}`);
      }

      const result = await response.json();
      console.log('[DEBUG] API Response:', result);
      
      // Transform backend response to frontend format
      return {
        id: result.id || uuidv4(),
        providerId: result.provider,
        providerName: config.providerName,
        baseUrl: result.api_base,
        apiKey: result.api_key,
        modelName: result.model_name,
        displayName: result.name,
        isActive: result.enabled,
        maxTokens: result.max_tokens,
        temperature: result.temperature,
        topP: result.top_p,
        description: result.description,
        tags: config.tags || [],
        createdAt: new Date(result.created_at || Date.now()),
        updatedAt: new Date(result.last_updated || Date.now()),
        status: (result.status || config.status || 'unknown') as const,  // 使用服务器返回的状态或提交的状态
        lastChecked: result.last_checked ? new Date(result.last_checked) : config.lastChecked
      } as ModelConfigInfo;
    } catch (error) {
      console.error('Model configuration creation failed:', error);
      if (error instanceof Error) {
        throw new Error(`Failed to create model configuration: ${error.message}`);
      }
      throw new Error('Failed to create model configuration');
    }
  }

  /**
   * 生成CSRF令牌
   */
  private getCSRFToken(): string {
    let token = sessionStorage.getItem('csrf_token');
    if (!token) {
      const array = new Uint8Array(32);
      crypto.getRandomValues(array);
      token = btoa(String.fromCharCode(...array));
      sessionStorage.setItem('csrf_token', token);
    }
    return token;
  }

  /**
   * 更新模型配置
   */
  async updateModelConfig(id: string, config: Partial<ModelConfigRequest>): Promise<ModelConfigInfo> {
    try {
      const response = await fetch(`${API_BASE}/model-configs/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        },
        body: JSON.stringify({
          name: config.displayName || config.modelName,
          provider: config.providerId,
          provider_name: config.providerName,
          model_name: config.modelName,
          api_key: config.apiKey,
          api_base: config.baseUrl,
          temperature: config.temperature,
          max_tokens: config.maxTokens,
          top_p: config.topP,
          enabled: config.isActive,
          description: config.description,
          status: config.status,  // 传递状态字段
          last_checked: config.lastChecked  // 传递最后检查时间
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      
      // Transform backend response to frontend format
      return {
        id: result.id || id,
        providerId: result.provider,
        providerName: config.providerName || result.provider,
        baseUrl: result.api_base,
        apiKey: result.api_key,
        modelName: result.model_name,
        displayName: result.name,
        isActive: result.enabled,
        maxTokens: result.max_tokens,
        temperature: result.temperature,
        topP: result.top_p,
        description: result.description,
        tags: config.tags || [],
        createdAt: new Date(result.created_at || Date.now()),
        updatedAt: new Date(result.last_updated || Date.now()),
        status: (result.status || config.status || 'unknown') as const,  // 使用服务器返回的状态或提交的状态
        lastChecked: result.last_checked ? new Date(result.last_checked) : config.lastChecked
      } as ModelConfigInfo;
    } catch (error) {
      console.error('Failed to update model configuration:', error);
      throw error;
    }
  }

  /**
   * 删除模型配置
   */
  async deleteModelConfig(id: string): Promise<void> {
    try {
      const response = await fetch(`${API_BASE}/model-configs/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${this.getToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error('Failed to delete model configuration:', error);
      throw error;
    }
  }

  /**
   * 测试模型连接
   */
  async testModelConnection(config: {baseUrl: string; apiKey: string; modelName?: string; providerId?: string; configId?: string}): Promise<ModelTestResult> {
    console.log('[FORCE] testModelConnection called with config:', { ...config, apiKey: '***masked***' });
    console.log('[FORCE] useMockData:', this.useMockData);
    console.log('[FORCE] API_BASE:', API_BASE);
    
    if (this.useMockData) {
      console.log('[DEBUG] Using mock test result');
      // 模拟测试延迟
      await new Promise(resolve => setTimeout(resolve, 1500));
      return this.getMockTestResult();
    }

    try {
      console.log('[FORCE] About to make API call to:', `${API_BASE}/model-configs/test`);
      const response = await fetch(`${API_BASE}/model-configs/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        },
        body: JSON.stringify(config)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const apiResponse = await response.json();
      if (this.debugMode) console.log('[DEBUG] Test response:', apiResponse);
      
      // 解析符合API规范的响应格式
      const result: ModelTestResult = {
        success: apiResponse.success,
        status: apiResponse.data?.status || (apiResponse.success ? 'healthy' : 'unhealthy'),
        responseTime: apiResponse.data?.responseTime || 0,
        message: apiResponse.message,
        modelInfo: apiResponse.data?.modelInfo
      };
      
      return result;
    } catch (error) {
      console.error('Failed to test model connection:', error);
      throw error;  // 直接抛出错误，不使用mock数据
    }
  }

  /**
   * 执行模型健康检查（使用后端存储的完整API key）
   */
  async checkModelHealth(configId: string): Promise<ModelTestResult> {
    if (this.debugMode) console.log('[DEBUG] Checking health for config:', configId);
    
    try {
      const response = await fetch(`${API_BASE}/model-configs/${configId}/check-health`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const apiResponse = await response.json();
      if (this.debugMode) console.log('[DEBUG] Health check response:', apiResponse);
      
      // 解析符合API规范的响应格式
      const result: ModelTestResult = {
        success: apiResponse.success,
        status: apiResponse.data?.status || 'unknown',
        responseTime: apiResponse.data?.responseTime || 0,
        message: apiResponse.message,
        modelInfo: apiResponse.data?.modelInfo
      };
      
      return result;
    } catch (error) {
      console.error('Failed to check model health:', error);
      throw error;
    }
  }

  /**
   * 并发批量测试模型健康状态
   */
  async batchTestModelHealth(configIds: string[]): Promise<Record<string, ModelTestResult>> {
    if (!this.checkRateLimit('batchTest')) {
      throw new Error('Rate limit exceeded. Please try again later.');
    }
    
    const results: Record<string, ModelTestResult> = {};
    const CONCURRENT_LIMIT = 3; // 并发限制
    
    try {
      // 获取所有配置
      const configs = await this.getModelConfigs();
      const configMap = new Map(configs.map(c => [c.id, c]));
      
      // 过滤有效的配置ID
      const validConfigIds = configIds.filter(id => configMap.has(id));
      
      // 分批并发处理
      for (let i = 0; i < validConfigIds.length; i += CONCURRENT_LIMIT) {
        const batch = validConfigIds.slice(i, i + CONCURRENT_LIMIT);
        
        const batchPromises = batch.map(async (configId) => {
          const config = configMap.get(configId);
          if (!config) return { configId, result: null };
          
          try {
            const result = await this.testModelConnection({
              baseUrl: config.baseUrl,
              apiKey: config.apiKey,
              modelName: config.modelName,
              providerId: config.providerId
            });
            return { configId, result };
          } catch (error) {
            return {
              configId,
              result: {
                success: false,
                status: 'unhealthy' as const,
                message: 'Test failed',
                responseTime: 0
              }
            };
          }
        });
        
        const batchResults = await Promise.allSettled(batchPromises);
        
        batchResults.forEach((promiseResult) => {
          if (promiseResult.status === 'fulfilled' && promiseResult.value.result) {
            results[promiseResult.value.configId] = promiseResult.value.result;
          }
        });
      }
      
    } catch (error) {
      console.error('Batch health test failed');
      throw new Error('Batch health test failed. Please try again.');
    }
    
    return results;
  }

  /**
   * 速率限制检查
   */
  private checkRateLimit(operation: string): boolean {
    const now = Date.now();
    const key = `${operation}_${Math.floor(now / 60000)}`;
    
    const current = this.rateLimitCache.get(key) || { count: 0, resetTime: now + 60000 };
    
    if (now > current.resetTime) {
      current.count = 0;
      current.resetTime = now + 60000;
    }
    
    if (current.count >= this.RATE_LIMIT_MAX) {
      return false;
    }
    
    current.count++;
    this.rateLimitCache.set(key, current);
    return true;
  }

  /**
   * 获取模型模板
   */
  async getModelTemplates(): Promise<ModelTemplate[]> {
    try {
      const response = await fetch(`${API_BASE}/model-templates`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to fetch model templates:', error);
      throw error;  // 直接抛出错误，不使用mock数据
    }
  }

  /**
   * 动态发现模型（从API获取可用模型）
   */
  async discoverModels(baseUrl: string, apiKey: string, provider: string): Promise<ModelDiscoveryResult> {
    try {
      const response = await fetch(`${API_BASE}/models/discover`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        },
        body: JSON.stringify({ 
          provider, 
          base_url: baseUrl.endsWith('/v1') ? baseUrl : `${baseUrl}/v1`,  // 确保有/v1后缀
          api_key: apiKey 
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to discover models:', error);
      throw error;
    }
  }

  /**
   * 导出配置
   */
  async exportConfigs(): Promise<string> {
    try {
      const configs = await this.getModelConfigs();
      return JSON.stringify(configs, null, 2);
    } catch (error) {
      console.error('Failed to export configurations:', error);
      throw error;
    }
  }

  /**
   * 验证配置数据（增强安全检查）
   */
  private validateConfig(config: ModelConfigRequest): { valid: boolean; errors: string[] } {
    const errors: string[] = [];
    
    // 基础字段验证
    for (const rule of VALIDATION_RULES) {
      const value = config[rule.field] as any;
      
      switch (rule.type) {
        case 'required':
          if (!value || (typeof value === 'string' && value.trim() === '')) {
            errors.push(rule.message);
          }
          break;
          
        case 'url':
          if (value) {
            const urlValidation = securityUtils.validateApiUrl(value);
            if (!urlValidation.valid) {
              errors.push(urlValidation.error || 'Invalid URL');
            }
          }
          break;
          
        case 'pattern':
          if (value && rule.pattern && !rule.pattern.test(value)) {
            errors.push(rule.message);
          }
          break;
          
        case 'length':
          if (value && typeof value === 'string') {
            if ((rule.min && value.length < rule.min) || (rule.max && value.length > rule.max)) {
              errors.push(rule.message);
            }
          }
          break;
      }
    }
    
    // API密钥格式验证
    if (config.apiKey) {
      const keyValidation = securityUtils.validateApiKeyFormat(config.providerId, config.apiKey);
      if (!keyValidation.valid) {
        errors.push(keyValidation.error || 'Invalid API key format');
      }
    }
    
    // 输入清理
    if (config.providerName) {
      config.providerName = securityUtils.sanitizeInput(config.providerName);
    }
    if (config.modelName) {
      config.modelName = securityUtils.sanitizeInput(config.modelName);
    }
    if (config.displayName) {
      config.displayName = securityUtils.sanitizeInput(config.displayName);
    }
    
    return { valid: errors.length === 0, errors };
  }

  /**
   * 检测恶意内容
   */
  private detectMaliciousContent(data: string): { safe: boolean; threats: string[] } {
    const threats: string[] = [];
    
    for (const pattern of MALICIOUS_PATTERNS) {
      if (pattern.test(data)) {
        threats.push(`Potential ${pattern.source.substring(0, 20)}... detected`);
      }
    }
    
    // 检查数据大小
    if (data.length > this.MAX_IMPORT_SIZE) {
      threats.push('Data size exceeds maximum allowed limit');
    }
    
    return { safe: threats.length === 0, threats };
  }

  /**
   * 安全导入配置（带恶意数据检测）
   */
  async importConfigs(configData: string): Promise<{ success: number; failed: number; errors: string[] }> {
    const results = { success: 0, failed: 0, errors: [] as string[] };
    
    try {
      // 恶意内容检测
      const securityCheck = this.detectMaliciousContent(configData);
      if (!securityCheck.safe) {
        throw new Error(`Security validation failed: ${securityCheck.threats.join(', ')}`);
      }
      
      // 解析JSON
      let configs: ModelConfigRequest[];
      try {
        configs = JSON.parse(configData);
      } catch (parseError) {
        throw new Error('Invalid JSON format in configuration data');
      }
      
      // 检查配置数量限制
      if (!Array.isArray(configs)) {
        throw new Error('Configuration data must be an array');
      }
      
      if (configs.length > this.MAX_IMPORT_CONFIGS) {
        throw new Error(`Too many configurations. Maximum allowed: ${this.MAX_IMPORT_CONFIGS}`);
      }
      
      // 验证每个配置
      const validConfigs: ModelConfigRequest[] = [];
      for (const [index, config] of configs.entries()) {
        // 基本类型检查
        if (!config || typeof config !== 'object') {
          results.errors.push(`Configuration ${index + 1}: Invalid configuration object`);
          results.failed++;
          continue;
        }
        
        // 字段验证
        const validation = this.validateConfig(config);
        if (!validation.valid) {
          results.errors.push(`Configuration ${index + 1}: ${validation.errors.join(', ')}`);
          results.failed++;
          continue;
        }
        
        // 额外的安全检查
        const configString = JSON.stringify(config);
        const configSecurityCheck = this.detectMaliciousContent(configString);
        if (!configSecurityCheck.safe) {
          results.errors.push(`Configuration ${index + 1}: Security validation failed`);
          results.failed++;
          continue;
        }
        
        validConfigs.push(config);
      }
      
      // 批量创建有效配置
      if (validConfigs.length > 0) {
        const importResults = await this.batchCreateConfigs(validConfigs);
        results.success = importResults.success;
        results.failed += importResults.failed;
        results.errors.push(...importResults.errors);
      }
      
    } catch (error) {
      console.error('Configuration import failed');
      throw new Error(`Import failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
    
    return results;
  }

  /**
   * 批量创建配置（优化并发处理）
   */
  private async batchCreateConfigs(configs: ModelConfigRequest[]): Promise<{ success: number; failed: number; errors: string[] }> {
    const results = { success: 0, failed: 0, errors: [] as string[] };
    const BATCH_SIZE = 5; // 并发批次大小
    
    // 分批处理以避免过多并发请求
    for (let i = 0; i < configs.length; i += BATCH_SIZE) {
      const batch = configs.slice(i, i + BATCH_SIZE);
      
      const batchPromises = batch.map(async (config, index) => {
        try {
          await this.createModelConfig(config);
          return { success: true, index: i + index };
        } catch (error) {
          return { 
            success: false, 
            index: i + index, 
            error: error instanceof Error ? error.message : 'Unknown error'
          };
        }
      });
      
      const batchResults = await Promise.allSettled(batchPromises);
      
      batchResults.forEach((result, batchIndex) => {
        if (result.status === 'fulfilled') {
          if (result.value.success) {
            results.success++;
          } else {
            results.failed++;
            results.errors.push(`Configuration ${result.value.index + 1}: ${result.value.error}`);
          }
        } else {
          results.failed++;
          results.errors.push(`Configuration ${i + batchIndex + 1}: Import failed`);
        }
      });
    }
    
    return results;
  }

  // 私有辅助方法

  private getToken(): string {
    // 从localStorage或其他存储中获取认证token
    return localStorage.getItem('authToken') || '';
  }

  // 注释：以下功能依赖后端/keys端点，该端点尚未实现，暂时禁用

  /**
   * 获取带密钥使用统计的配置（暂未使用）
   */
  /*
  async getConfigsWithUsageStats(): Promise<ModelConfigInfo[]> {
    const configs = await this.getModelConfigs();
    const enrichedConfigs = await Promise.all(
      configs.map(async (config) => {
        if (config.keyId) {
          try {
            const stats = await apiKeyService.getKeyUsageStats(config.keyId);
            return {
              ...config,
              usageStats: stats
            };
          } catch (error) {
            console.error(`Failed to get usage stats for ${config.id}:`, error);
          }
        }
        return config;
      })
    );
    return enrichedConfigs;
  }
  */

  /**
   * 轮换配置的API密钥（暂未使用）
   */
  /*
  async rotateConfigKey(configId: string, newKey: string): Promise<ModelConfigInfo> {
    const configs = await this.getModelConfigs();
    const config = configs.find(c => c.id === configId);

    if (!config) {
      throw new Error('配置不存在');
    }

    if (config.keyId) {
      await apiKeyService.rotateKey(config.keyId, newKey);
    }

    return await this.updateModelConfig(configId, { apiKey: newKey });
  }
  */

  private getMockConfigs(): ModelConfigInfo[] {
    return [
      {
        id: 'openai-gpt4',
        providerId: 'openai',
        providerName: 'OpenAI',
        baseUrl: 'https://api.openai.com/v1',
        apiKey: 'sk-***masked***',
        modelName: 'gpt-4',
        displayName: 'GPT-4',
        isActive: true,
        status: 'healthy',
        lastChecked: new Date(),
        createdAt: new Date('2025-09-15'),
        maxTokens: 8192,
        costPerToken: 0.00003,
        responseTime: 280,
        errorCount: 0,
        uptime: 168,
        healthScore: 98
      },
      {
        id: 'claude-anyrouter',
        providerId: 'claude',
        providerName: 'Anthropic Claude',
        baseUrl: 'https://anyrouter.top',
        apiKey: 'sk-ant-***masked***',
        modelName: 'claude-4.1',
        displayName: 'Claude 4.1 (AnyRouter)',
        isActive: true,
        status: 'warning',
        lastChecked: new Date(Date.now() - 10 * 60 * 1000),
        createdAt: new Date('2025-09-18'),
        maxTokens: 200000,
        costPerToken: 0.00002,
        responseTime: 1800,
        errorCount: 3,
        uptime: 72,
        healthScore: 75,
        lastError: '响应超时'
      },
      {
        id: 'deepseek-default',
        providerId: 'deepseek',
        providerName: 'DeepSeek',
        baseUrl: 'https://api.deepseek.com/v1',
        apiKey: 'sk-proj-***masked***',
        modelName: 'deepseek-chat',
        displayName: 'DeepSeek Chat',
        isActive: true,
        status: 'unhealthy',
        lastChecked: new Date(Date.now() - 2 * 60 * 60 * 1000),
        createdAt: new Date('2025-09-20'),
        maxTokens: 32000,
        costPerToken: 0.000002,
        responseTime: 0,
        errorCount: 12,
        uptime: 0,
        healthScore: 15,
        lastError: 'API密钥无效'
      }
    ];
  }

  private getMockTestResult(): ModelTestResult {
    const success = Math.random() > 0.3;
    return {
      success,
      status: success ? 'healthy' : 'unhealthy',
      responseTime: Math.floor(Math.random() * 2000) + 500,
      message: success 
        ? '连接测试成功！模型响应正常。' 
        : '连接测试失败：无效的API密钥或网络连接问题。',
      ...(success && {
        modelInfo: {
          name: 'test-model',
          version: '1.0',
          maxTokens: 4096
        }
      })
    };
  }

  private getMockTemplates(): ModelTemplate[] {
    return [
      {
        providerId: 'openai',
        providerName: 'OpenAI',
        defaultBaseUrl: 'https://api.openai.com/v1',
        authType: 'bearer',
        suggestedModels: [
          { name: 'gpt-4', displayName: 'GPT-4', description: '最强大的GPT模型', maxTokens: 8192, isRecommended: true },
          { name: 'gpt-4-turbo', displayName: 'GPT-4 Turbo', description: '更快的GPT-4版本', maxTokens: 128000 },
          { name: 'gpt-3.5-turbo', displayName: 'GPT-3.5 Turbo', description: '高效的对话模型', maxTokens: 4096 }
        ]
      },
      {
        providerId: 'claude',
        providerName: 'Anthropic Claude',
        defaultBaseUrl: 'https://api.anthropic.com',
        authType: 'apikey',
        suggestedModels: [
          { name: 'claude-4.1', displayName: 'Claude 4.1', description: '最新版本Claude', maxTokens: 200000, isRecommended: true },
          { name: 'claude-opus-4.1', displayName: 'Claude Opus 4.1', description: 'Claude最强版本', maxTokens: 200000 },
          { name: 'claude-sonnet-3.5', displayName: 'Claude Sonnet 3.5', description: '平衡性能版本', maxTokens: 200000 }
        ]
      },
      {
        providerId: 'deepseek',
        providerName: 'DeepSeek',
        defaultBaseUrl: 'https://api.deepseek.com/v1',
        authType: 'apikey',
        suggestedModels: [
          { name: 'deepseek-chat', displayName: 'DeepSeek Chat', description: '通用对话模型', maxTokens: 32000, isRecommended: true },
          { name: 'deepseek-coder', displayName: 'DeepSeek Coder', description: '代码生成专用', maxTokens: 32000 }
        ]
      }
    ];
  }
}

export default new ModelConfigService();